
const express = require('express')
const cors = require('cors')
const helmet = require('helmet')
const morgan = require('morgan')
const { createServer } = require('http')
const { Server } = require('socket.io')
const cron = require('node-cron')

const app = express()
const server = createServer(app)
const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"]
  }
})

// 中间件
app.use(helmet())
app.use(cors())
app.use(morgan('combined'))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 路由
app.use('/api/procurement', require('./routes/procurement'))
app.use('/api/warehouse', require('./routes/warehouse'))
app.use('/api/cold-chain', require('./routes/cold-chain'))
app.use('/api/store', require('./routes/store'))
app.use('/api/inventory', require('./routes/inventory'))
app.use('/api/dashboard', require('./routes/dashboard'))

// Socket.io 连接处理
io.on('connection', (socket) => {
  console.log('客户端已连接:', socket.id)
  
  socket.on('join-room', (room) => {
    socket.join(room)
    console.log(`客户端 ${socket.id} 加入房间 ${room}`)
  })
  
  socket.on('disconnect', () => {
    console.log('客户端已断开:', socket.id)
  })
})

// 定时任务：每分钟检查风险预警
cron.schedule('* * * * *', () => {
  checkRiskAlerts()
})

const checkRiskAlerts = () => {
  // 模拟风险检查
  const alerts = [
    {
      id: Date.now(),
      type: 'warning',
      timestamp: new Date().toLocaleString('zh-CN'),
      message: '检测到冷链温度异常'
    }
  ]
  
  io.emit('risk-alert', alerts)
}

const PORT = process.env.PORT || 3001
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`)
})

module.exports = { app, io }
